<template>
  <div>
    <h1>计算属性</h1>
    <div>
      在模板中计算：
      {{ author.books.length > 1 ? author.books.join('-') : author.books[0] }}
    </div>

    <div v-for="item in 5" :key="item">
      计算属性：
      {{ compBooksStr }}
    </div>
    <div v-for="item in 3" :key="item">
      自定义函数：
      {{ funcBooksStr() }}
    </div>
    <input type="text" v-model="bookName" />
    <button type="button" @click="addNewBook">新加一本书</button>
  </div>
</template>
<script lang="ts">
export default {
  name: 'Study3StuDemo13'
}
</script>
<script setup lang="ts">
import { computed, reactive, ref } from 'vue'

const bookName = ref('')
const author = reactive({
  name: 'John Doe',
  books: ['金瓶梅', '活着', '小王子', '让富婆爱上我', '广州富婆通讯录', '让高富帅爱上我']
})

const addNewBook = () => {
  try {
    if (!bookName.value) {
      throw new Error('请输入输的名字')
    }
    author.books.push(bookName.value)
  } catch (error: any) {
    alert(error.msg)
  }
}

// 计算属性
// 1.计算属性函数的结果会缓存，除非计算属性相关的状态变量改变才会重新生成结果
// 2.传入getter函数，返回一个ref
const compBooksStr = computed(() => {
  console.log('computed被调用，结果重新计算')

  return author.books.length > 1 ? author.books.join('-') : author.books[0]
})

// 普通函数
function funcBooksStr() {
  console.log('自定函数被调用，结果重新计算')

  return author.books.length > 1 ? author.books.join('-') : author.books[0]
}

// 可写计算属性
const compBooksStrW = computed({
  get: () => {
    return author.books.length > 1 ? author.books.join('-') : author.books[0]
  },
  set: (val) => {
    console.log(val)
    author.books = [...author.books, val]
  }
})

compBooksStrW.value = '毛选'
compBooksStrW.value = '马克'
compBooksStrW.value = '针灸大成'
</script>

<style></style>
